package pub.developers.forum.app.manager;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import pub.developers.forum.api.request.file.FileUploadImgRequest;
import pub.developers.forum.app.support.IsLogin;
import pub.developers.forum.domain.service.FileService;
import pub.developers.forum.domain.service.OssFileService;

import javax.annotation.Resource;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;


@Component
@Slf4j
public class FileManager {

    @Resource
    private FileService fileService;

    @Resource
    private OssFileService ossFileService;

    @IsLogin
    public String uploadImg(FileUploadImgRequest request) {
        return fileService.uploadImg(request.getBase64(), request.getFileName());
    }

    //删除七牛云上指定的照片
    public String deleteAvatar(String avatarName)
    {
        avatarName = avatarName.split("\\\\")[1];
        return fileService.deleteImg(avatarName);
    }


    //将图片上传到Oss
    @IsLogin
    public String uploadImgOss(FileUploadImgRequest request) throws ParseException {
        String result = ossFileService.uploadImg(request.getBase64(), request.getFileName() , request.getType());
        return result;
    }

    //删除Oss上指定的照片
    public String deleteAvatarOss(String avatarName)
    {
        //////System.out.println(avatarName);
        try {
            // 将URL字符串解析为URI对象
            URI uri = new URI(avatarName);
            // 从URI中获取路径部分
            String path = uri.getPath();
            // 使用 "/" 分割路径，然后获取最后一个部分，即文件名
            String[] parts = path.split("/");
            avatarName= parts[parts.length - 2 ] +"/"+parts[parts.length - 1];
            //////System.out.println("提取的文件名: " + avatarName);
        } catch (URISyntaxException e) {
            log.error(e.getMessage());
            return "error";
        }
        ////System.out.println("图片名称" +avatarName);
        return ossFileService.deleteImg(avatarName);
    }

}
